const timeUtil = {
  getDate(unixTime) {
    const date = new Date(unixTime)
    return `${date.getFullYear().toString().substring(2)}/${date.getMonth() + 1}/${date.getDate()}`
  },
  getTime(unixTime) {
    const date = new Date(unixTime)
    const hours = date.getHours()
    const formatedHours = hours >= 10 ? hours : '0' + hours
    const minutes = date.getMinutes()
    const formatedMinutes = minutes >= 10 ? minutes : '0' + minutes
    const seconds = date.getSeconds()
    const formatedSeconds = seconds >= 10 ? seconds : '0' + seconds
    return `${formatedHours}:${formatedMinutes}:${formatedSeconds}`
  },
  getDateTime(unixTime) {
    const date = new Date(unixTime)
    if (Number.isNaN(date.getHours())) {
      date = new Date();
    }
    const hours = date.getHours()
    const formatedHours = hours >= 10 ? hours : '0' + hours
    const minutes = date.getMinutes()
    const formatedMinutes = minutes >= 10 ? minutes : '0' + minutes
    const seconds = date.getSeconds()
    const formatedSeconds = seconds >= 10 ? seconds : '0' + seconds
    console.log(unixTime);
    console.log(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${formatedHours}:${formatedMinutes}:${formatedSeconds}`
  }
}

function getQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  var r = window.location.search.substr(1).match(reg)
  if (r != null) {
    return unescape(r[2])
  }
  return null
}

function screenSize() {
  const rootEle = document.getElementById('root')
  if (rootEle.offsetHeight / rootEle.offsetWidth <= 1.4) {
    let domHeight = document.body.offsetHeight
    console.log(rootEle.offsetHeight / rootEle.offsetWidth)
    rootEle.style.width = domHeight / 1.5 + 'px'
    rootEle.style.height = domHeight + 'px'
    rootEle.style.margin = 'auto'
  }
}

function init() {
  screenSize()
  const token = getQueryString('token')
  const areaCode = getQueryString('areaCode')
  Cookies.set('areaCode', areaCode)
  Cookies.set('token', token)
  const shopping = getQueryString('shopping')
  if (shopping) {
    window.location.hash = 'Mall'
  }
  global.fetchJson = (url, opt, query) => {
    const optAppend = Object.assign({
      headers: {
        Authorization: Cookies.get('token'),
        'Content-type': 'application/json'
      }
    }, opt)
    var requestUrl = url
    if (optAppend.method === 'GET' && query) {
      requestUrl += '?' + queryString.stringify(query)
    }
    return fetch(requestUrl, optAppend).then(res => {
      if (res.ok) {
        return res.json()
      }
      throw new Error('network error')
    })
  }

  const roomNo = getQueryString('roomNo')
  if (roomNo) {
    let url = `${config.pre}/crowd/room/join/${Cookies.get('areaCode')}`
    let opt = {
      method: 'POST',
      body: JSON.stringify({ roomNo })
    }
    fetchJson(url, opt).then(data => {
      console.log(data)
      if (data.result) {
      } else {
        window.location.href = data.data
      }
    })
  }
}

function nickname(value) {
  if (!value) { return '' }
  // 中文、英文、数字但不包括下划线等符号 可以输入含有^%&',;=?$\"等字符
  // [^%&',;=?$\x22]+
  const regPattern = /^[\u4E00-\u9FA5A-Za-z0-9_^%&',;=?$\x22]+$/
  const reValues = []
  for (let i = 0; i < value.length; i++) {
    reValues.push(value[i])
  }
  // const reValue = reValues.join('')
  // console.log('reValue', reValue);
  const rets = []
  reValues.forEach(reval => {
    const ret = reval.match(regPattern) ? reval.match(regPattern).join('') : ''
    rets.push(ret)
  })
  // const ret = reValue.match(regPattern) ? reValue.match(regPattern).join('') : ''
  const finalRet = rets.join('')
  if (finalRet.length > 6) {
    return (finalRet.substring(0, 4) + '...')
  }
  return finalRet
}

function maxLength(value, length = 10) {
  if (!value) { return '' }
  const reValues = []
  for (let i = 0; i < value.length; i++) {
    reValues.push(value[i])
  }
  if (reValues.length > length) {
    return (reValues.join('').substring(0, length - 2) + '..')
  }
  return reValues.join('')
}

const gameUtil = {
  classicBullRules(rule) {
    // 玩法：0斗公牛；1抢庄；2牛牛庄家；3牌大坐庄；4轮庄；5霸王庄
    const ruleTextList = ['斗公牛', '抢庄', '牛牛庄家', '牌大坐庄', '轮庄', '霸王庄']
    const ruleText = ruleTextList[rule.ruleType]
    const visibleText = '可见牌' + rule.showCardCount + '张'
    return {
      ruleName: `${ruleText}/${rule.turns * 15 + '回合'}/${visibleText}`,
      headUrl: 'img/gameIcon/classic-bull.png',
      name: '经典牛牛'
    }
  },
  fightBullRules(rule) {
    const visibleText = '可见牌' + rule.showCardCount + '张'
    return {
      ruleName: `${rule.turns + '轮庄'}/${visibleText}`,
      headUrl: 'img/gameIcon/fight-bull.png',
      name: '斗公牛'
    }
  },
  majiangRules(rule) {
    const ruleTextList = ['一码全中', '两个码', '四个码', '六个码', '八个码']
    const ruleText = ruleTextList[rule.ruleType - 1]
    return {
      ruleName: `${ruleText}/${rule.turns * 8 + '回合'}`,
      headUrl: 'img/gameIcon/majiang.png',
      name: '红中麻将'
    }
  },
  dianziBullRules(rule) {
    const ruleName = rule.ruleType === 6 ? '牛牛几倍' : '牛牛相差'
    const visibleText = '可见牌' + rule.showCardCount + '张'
    return {
      ruleName: `${ruleName}/${rule.turns * 15 + '回合'}/${visibleText}`,
      headUrl: 'img/gameIcon/dianzi-bull.png',
      name: '点子牛'
    }
  },
  jinhuaRules(rule) {
    var ruleText
    if (rule.ruleType === 1) {
      ruleText = '一十回合封顶'
    } else if (rule.ruleType === 2) {
      ruleText = '二十回合封顶'
    } else if (rule.ruleType === 3) {
      ruleText = '三十回合封顶'
    }
    // const visibleText = '可见牌' + rule.showCardCount + '张'
    return {
      ruleName: `${ruleText}/${rule.turns * 8 + '回合'}`,
      headUrl: 'img/gameIcon/wansanzhang.png',
      name: '玩金花'
    }
  },
  sangongRules(rule) {
    var ruleText
    if (rule.ruleType === 1) {
      ruleText = '抢庄'
    } else if (rule.ruleType === 2) {
      ruleText = '三公庄家'
    } else if (rule.ruleType === 3) {
      ruleText = '牌大坐庄'
    } else if (rule.ruleType === 4) {
      ruleText = '轮庄'
    } else if (rule.ruleType === 5) {
      ruleText = '霸王庄'
    }
    const visibleText = '可见牌' + rule.showCardCount + '张'
    return {
      ruleName: `${ruleText}/${rule.turns * 15 + '回合'}/${visibleText}`,
      headUrl: 'img/gameIcon/sangong.png',
      name: '三公'
    }
  },
  pjchuanRules(rule) {
    const visibleText = '可见牌' + rule.showCardCount + '张'
    return {
      ruleName: `${rule.turns * 15 + '回合'}/${visibleText}`,
      headUrl: 'img/gameIcon/sangong.png',
      name: '平江划船'
    }
  },
  runRules(rule, totalTurns) {
    var ruleText
    if (rule.ruleType === 1) {
      ruleText = '15张'
    } else if (rule.ruleType === 2) {
      ruleText = '16张'
    }
    // const visibleText = '可见牌' + rule.showCardCount + '张'
    // const huiheStr = totalTurns ? '/' + totalTurns + '回合' : ''
    return {
      ruleName: `${ruleText}/${rule.turns * 8 + '回合'}`,
      // ruleName: `${ruleText}${huiheStr}`,
      headUrl: 'img/gameIcon/pdk-icon.png',
      name: '跑得快'
    }
  },
  znRules(rule) {
    const ruleTextList = ['一个码', '两个码', '三个码']
    const ruleText = ruleTextList[rule.ruleType - 1]
    return {
      ruleName: `${ruleText}/${rule.turns * 8 + '回合'}`,
      headUrl: 'img/gameIcon/pingjiang-majiang.png',
      name: '平江扎鸟'
    }
  },
  xiantaoRules(rule) {
    // const ruleTextList = ['一码全中', '两个码', '四个码', '六个码', '八个码']
    const turns = [3, 4, 6];
    const ruleText = rule.leper ? '8癞子' : '4癞子';
    return {
      ruleName: `${ruleText}/${turns[rule.turns - 1] + '回合'}`,
      headUrl: 'img/gameIcon/majiang.png',
      name: '仙桃千分'
    }
  }
}

export default { timeUtil, init, getQueryString, nickname, gameUtil, maxLength }